package com.eduagent.xwqeduagent.controller;

import com.eduagent.xwqeduagent.api.characterRecognition.UniversalFileRecognition.Base64RecognitionRequest;
import com.eduagent.xwqeduagent.api.characterRecognition.UniversalFileRecognition.UniversalFileRecognitionResult;
import com.eduagent.xwqeduagent.api.characterRecognition.UniversalFileRecognition.UniversalFileRecognitionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 通用文档识别OCR识别控制器（仅仅支持图片）
 */
@Slf4j
@RestController
@RequestMapping("/ocr")
public class UniversalFileRecognitionController {

    @Autowired
    private UniversalFileRecognitionService recognitionService;

    /**
     * 上传图片进行OCR识别
     *
     * @param file 上传的图片文件
     * @param uid 用户ID（可选）
     * @return OCR识别结果
     */
    @PostMapping("/recognize")
    public ResponseEntity<?> recognizeImage(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "uid", required = false) String uid) {
        try {
            // 调用服务进行识别
            UniversalFileRecognitionResult result = recognitionService.recognizeImage(file, uid);
            
            // 返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("result", result);
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            // 参数错误
            log.warn("参数错误：{}", e.getMessage());
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        } catch (IOException | InterruptedException e) {
            // 服务调用错误
            log.error("OCR识别失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("error", "OCR识别失败：" + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 上传图片进行OCR识别（支持高级参数）
     *
     * @param file 上传的图片文件
     * @param uid 用户ID（可选）
     * @param resultOption 输出结果级别
     * @param resultFormat 输出结果格式
     * @param outputType 结果输出方式
     * @param exifOption 是否解析exif头
     * @param alphaOption 是否解析alpha通道
     * @param markdownElementOption markdown元素选项
     * @param sedElementOption sed元素选项
     * @param rotationMinAngle 图像旋转角度阈值
     * @return OCR识别结果
     */
    @PostMapping("/recognize/advanced")
    public ResponseEntity<?> recognizeImageAdvanced(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "uid", required = false) String uid,
            @RequestParam(value = "resultOption", required = false) String resultOption,
            @RequestParam(value = "resultFormat", required = false) String resultFormat,
            @RequestParam(value = "outputType", required = false) String outputType,
            @RequestParam(value = "exifOption", required = false) String exifOption,
            @RequestParam(value = "alphaOption", required = false) String alphaOption,
            @RequestParam(value = "markdownElementOption", required = false) String markdownElementOption,
            @RequestParam(value = "sedElementOption", required = false) String sedElementOption,
            @RequestParam(value = "rotationMinAngle", required = false) Float rotationMinAngle) {
        try {
            // 调用服务进行识别
            UniversalFileRecognitionResult result = recognitionService.recognizeImageWithAdvancedOptions(
                file, uid, resultOption, resultFormat, outputType, exifOption, 
                alphaOption, markdownElementOption, sedElementOption, rotationMinAngle);
            
            // 返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("result", result);
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            // 参数错误
            log.warn("参数错误：{}", e.getMessage());
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        } catch (IOException | InterruptedException e) {
            // 服务调用错误
            log.error("OCR识别失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("error", "OCR识别失败：" + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 使用Base64编码的图片进行OCR识别
     *
     * @param request 识别请求
     * @return OCR识别结果
     */
    @PostMapping("/recognize/base64")
    public ResponseEntity<?> recognizeBase64Image(@RequestBody Base64RecognitionRequest request) {
        try {
            // 参数验证
            if (request == null || request.getBase64Content() == null || request.getBase64Content().trim().isEmpty()) {
                throw new IllegalArgumentException("Base64编码的图片内容不能为空");
            }
            
            if (request.getImageFormat() == null || request.getImageFormat().trim().isEmpty()) {
                throw new IllegalArgumentException("图片格式不能为空");
            }
            
            // 检查是否有高级参数
            boolean hasAdvancedOptions = request.getResultOption() != null || 
                                         request.getResultFormat() != null || 
                                         request.getOutputType() != null || 
                                         request.getExifOption() != null || 
                                         request.getAlphaOption() != null ||
                                         request.getMarkdownElementOption() != null || 
                                         request.getSedElementOption() != null || 
                                         request.getRotationMinAngle() != null;
            
            UniversalFileRecognitionResult result;
            if (hasAdvancedOptions) {
                // 使用高级参数调用服务
                result = recognitionService.recognizeBase64ImageWithAdvancedOptions(request);
            } else {
                // 使用基本参数调用服务
                result = recognitionService.recognizeBase64Image(
                    request.getBase64Content(), 
                    request.getImageFormat(),
                    request.getUid()
                );
            }
            
            // 返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("result", result);
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            // 参数错误
            log.warn("参数错误：{}", e.getMessage());
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        } catch (IOException | InterruptedException e) {
            // 服务调用错误
            log.error("OCR识别失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("error", "OCR识别失败：" + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }

    /**
     * 获取纯文本识别内容
     * 
     * @param file 上传的图片文件
     * @param uid 用户ID（可选）
     * @return 纯文本内容
     */
    @PostMapping("/recognize/text")
    public ResponseEntity<?> recognizeImageText(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "uid", required = false) String uid) {
        try {
            // 调用服务进行识别
            UniversalFileRecognitionResult result = recognitionService.recognizeImage(file, uid);
            
            // 返回纯文本内容
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("text", result.getPlainText());
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException e) {
            // 参数错误
            log.warn("参数错误：{}", e.getMessage());
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("error", e.getMessage());
            return ResponseEntity.badRequest().body(response);
        } catch (IOException | InterruptedException e) {
            // 服务调用错误
            log.error("OCR识别失败", e);
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("error", "OCR识别失败：" + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
} 